import {
  dictAdd,
  editDic,
  getAllDicitionaryList,
  removeDicItem
} from "@/api/system";
import {
  DictionaryAddRequest,
  DictionaryResponse,
  DictionaryUpdateRequest,
  treeDicitionaryList
} from "@/api/system/system";
import { convertDicTree } from "@/utils/tree";
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useDicitionaryStore = defineStore(
  "pure-dicitionary",
  () => {
    const dicitionaryList = ref<DictionaryResponse[]>([]);
    // 获取字典列表
    const getDicitionaryList = async () => {
      const res = await getAllDicitionaryList();
      if (res.code === 0) {
        dicitionaryList.value = res.data;
      }
    };
    // 树形结构的dicitionary
    const treeDicitionaryList = computed<treeDicitionaryList[]>(() => {
      return dicitionaryList.value.length
        ? convertDicTree(dicitionaryList.value)
        : [];
    });
    // 添加字典节点
    const addDicItem = async (data: DictionaryAddRequest) => {
      const res = await dictAdd(data);
      if (res.code === 0) {
        ElMessage.success("添加成功");
        getDicitionaryList();
      }
    };
    // 编辑字典节点
    const editItem = async (data: DictionaryUpdateRequest) => {
      const res = await editDic(data);
      if (res.code === 0) {
        ElMessage.success("修改成功");
        getDicitionaryList();
      }
    };
    // 删除字典节点
    const delDicitionaryItem = async (id: string) => {
      const res = await removeDicItem(id);
      if (res.code === 0) {
        ElMessage.success("删除成功");
        getDicitionaryList();
      }
    };
    return {
      dicitionaryList,
      getDicitionaryList,
      treeDicitionaryList,
      delDicitionaryItem,
      addDicItem,
      editItem
    };
  },
  {
    // 开启本地存储
    persist: true
  }
);
